import 'package:meco/common/index.dart';
import 'package:meco/common/models/ceramic_interaction_model.dart';
import 'package:meco/common/models/ceramic_model.dart';
import 'ceramic_repository.dart';
import '../services/database_service.dart';

/// 定义一个接口，用于接收陶瓷交互状态更新
abstract class CeramicInteractionObserver {
  void onLikeStatusChanged(int userId, int ceramicId, bool isLiked);
  void onFavoriteStatusChanged(int userId, int ceramicId, bool isFavorited);
}

class CeramicInteractionRepository {
  final DatabaseService _databaseService = DatabaseService();
  final CeramicRepository _ceramicRepository = CeramicRepository();

  // 静态观察者列表，用于通知状态变化
  static final List<CeramicInteractionObserver> _observers = [];

  // 添加观察者
  static void addObserver(CeramicInteractionObserver observer) {
    if (!_observers.contains(observer)) {
      _observers.add(observer);
    }
  }

  // 移除观察者
  static void removeObserver(CeramicInteractionObserver observer) {
    _observers.remove(observer);
  }

  // 通知点赞状态变化
  void _notifyLikeStatusChanged(int userId, int ceramicId, bool isLiked) {
    for (var observer in _observers) {
      observer.onLikeStatusChanged(userId, ceramicId, isLiked);
    }
  }

  // 通知收藏状态变化
  void _notifyFavoriteStatusChanged(
    int userId,
    int ceramicId,
    bool isFavorited,
  ) {
    for (var observer in _observers) {
      observer.onFavoriteStatusChanged(userId, ceramicId, isFavorited);
    }
  }

  // 表名
  final String _likesTableName = 'ceramic_likes';
  final String _favoritesTableName = 'ceramic_favorites';

  // 点赞陶瓷作品
  Future<bool> likeCeramic(int userId, int ceramicId) async {
    final db = await _databaseService.database;
    final now = DateTime.now();

    try {
      // 检查是否已点赞
      final exists = await hasLiked(userId, ceramicId);
      if (exists) {
        return true; // 已经点赞过了
      }

      // 创建点赞记录
      final like = CeramicLike(
        userId: userId,
        ceramicId: ceramicId,
        createdAt: now,
        updatedAt: now,
      );

      final id = await db.insert(_likesTableName, like.toJson());

      if (id > 0) {
        // 更新作品的点赞数
        await _ceramicRepository.incrementLikeCount(ceramicId);
        // 通知观察者点赞状态变化
        _notifyLikeStatusChanged(userId, ceramicId, true);
        return true;
      }

      return false;
    } catch (e) {
      print('点赞失败: $e');
      return false;
    }
  }

  // 取消点赞陶瓷作品
  Future<bool> unlikeCeramic(int userId, int ceramicId) async {
    final db = await _databaseService.database;

    try {
      // 删除点赞记录
      final count = await db.delete(
        _likesTableName,
        where: 'user_id = ? AND ceramic_id = ?',
        whereArgs: [userId, ceramicId],
      );

      if (count > 0) {
        // 更新作品的点赞数
        await _ceramicRepository.decrementLikeCount(ceramicId);
        // 通知观察者点赞状态变化
        _notifyLikeStatusChanged(userId, ceramicId, false);
        return true;
      }

      return false;
    } catch (e) {
      print('取消点赞失败: $e');
      return false;
    }
  }

  // 检查用户是否已点赞陶瓷作品
  Future<bool> hasLiked(int userId, int ceramicId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> result = await db.query(
      _likesTableName,
      where: 'user_id = ? AND ceramic_id = ?',
      whereArgs: [userId, ceramicId],
      limit: 1,
    );

    return result.isNotEmpty;
  }

  // 获取陶瓷作品的所有点赞
  Future<List<CeramicLike>> getCeramicLikes(int ceramicId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _likesTableName,
      where: 'ceramic_id = ?',
      whereArgs: [ceramicId],
    );

    return List.generate(maps.length, (i) => CeramicLike.fromJson(maps[i]));
  }

  // 收藏陶瓷作品
  Future<bool> favoriteCeramic(int userId, int ceramicId) async {
    final db = await _databaseService.database;
    final now = DateTime.now();

    try {
      // 检查是否已收藏
      final exists = await hasFavorited(userId, ceramicId);
      if (exists) {
        return true; // 已经收藏过了
      }

      // 创建收藏记录
      final favorite = CeramicFavorite(
        userId: userId,
        ceramicId: ceramicId,
        createdAt: now,
        updatedAt: now,
      );

      final id = await db.insert(_favoritesTableName, favorite.toJson());

      if (id > 0) {
        // 更新作品的收藏数
        await _ceramicRepository.incrementFavoriteCount(ceramicId);
        // 通知观察者收藏状态变化
        _notifyFavoriteStatusChanged(userId, ceramicId, true);
        return true;
      }

      return false;
    } catch (e) {
      print('收藏失败: $e');
      return false;
    }
  }

  // 取消收藏陶瓷作品
  Future<bool> unfavoriteCeramic(int userId, int ceramicId) async {
    final db = await _databaseService.database;

    try {
      // 删除收藏记录
      final count = await db.delete(
        _favoritesTableName,
        where: 'user_id = ? AND ceramic_id = ?',
        whereArgs: [userId, ceramicId],
      );

      if (count > 0) {
        // 更新作品的收藏数
        await _ceramicRepository.decrementFavoriteCount(ceramicId);
        // 通知观察者收藏状态变化
        _notifyFavoriteStatusChanged(userId, ceramicId, false);
        return true;
      }

      return false;
    } catch (e) {
      print('取消收藏失败: $e');
      return false;
    }
  }

  // 检查用户是否已收藏陶瓷作品
  Future<bool> hasFavorited(int userId, int ceramicId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> result = await db.query(
      _favoritesTableName,
      where: 'user_id = ? AND ceramic_id = ?',
      whereArgs: [userId, ceramicId],
      limit: 1,
    );

    return result.isNotEmpty;
  }

  // 获取用户收藏的所有陶瓷作品ID
  Future<List<int>> getUserFavoriteCeramicIds(int userId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _favoritesTableName,
      columns: ['ceramic_id'],
      where: 'user_id = ?',
      whereArgs: [userId],
    );

    return maps.map((map) => map['ceramic_id'] as int).toList();
  }

  // 获取用户点赞的所有陶瓷作品ID
  Future<List<int>> getUserLikedCeramicIds(int userId) async {
    final db = await _databaseService.database;

    final List<Map<String, dynamic>> maps = await db.query(
      _likesTableName,
      columns: ['ceramic_id'],
      where: 'user_id = ?',
      whereArgs: [userId],
    );

    return maps.map((map) => map['ceramic_id'] as int).toList();
  }

  // 获取用户收藏过的陶瓷作品
  Future<List<Ceramic>> getFavoritedCeramics(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT c.* FROM ceramics c
        INNER JOIN ceramic_favorites f ON c.id = f.ceramic_id
        WHERE f.user_id = ?
        ORDER BY f.created_at DESC
      ''',
        [userId],
      );

      return List.generate(maps.length, (i) => Ceramic.fromJson(maps[i]));
    } catch (e) {
      print('获取用户收藏陶瓷错误: $e');
      return [];
    }
  }

  // 获取用户点赞过的陶瓷作品
  Future<List<Ceramic>> getLikedCeramics(int userId) async {
    try {
      final db = await _databaseService.database;
      final List<Map<String, dynamic>> maps = await db.rawQuery(
        '''
        SELECT c.* FROM ceramics c
        INNER JOIN ceramic_likes l ON c.id = l.ceramic_id
        WHERE l.user_id = ?
        ORDER BY l.created_at DESC
      ''',
        [userId],
      );

      return List.generate(maps.length, (i) => Ceramic.fromJson(maps[i]));
    } catch (e) {
      print('获取用户点赞陶瓷错误: $e');
      return [];
    }
  }
}
